<script setup lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, computed, useSlots, onMounted, onUnmounted } from "vue";
// import ReSegmented, { type OptionsType } from "@/components/ReSegmented";
// import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
// import { drawLineChart, drawPieChart, drawBarChart, drawStackingBarChart } from "../chart";
import * as echarts from "echarts";
import { Download, ViewModule } from "@px-ui/icons-vue";
import { updateProduction, getProductDataAPI, getConsumptionMeasurementSummary } from "@/api/energy/consumeMeasure";
import { PxMessage } from "px-ui";

const { proxy }: any = getCurrentInstance();
const props = defineProps({
  queryParams: {
    type: Object,
    default: () => {}
  },
  currentNode: {
    type: String,
    default: ""
  }
});
// const obj = {
//   costSummaryTable: [
//     {
//       system: "废水系统",
//       summaryCost: 8704.2436104,
//       electricityCost: null,
//       waterCost: null,
//       ngCost: null,
//       steamCost: null,
//       hotCost: null,
//       gasCost: 8704.2436104
//     },
//     {
//       system: "UPW纯水验证线系统",
//       summaryCost: 21595.1901,
//       electricityCost: null,
//       waterCost: null,
//       ngCost: null,
//       steamCost: null,
//       hotCost: null,
//       gasCost: 21595.1901
//     },
//     {
//       system: "UPW纯水生产线系统",
//       summaryCost: 108094.4721604894,
//       electricityCost: null,
//       waterCost: null,
//       ngCost: null,
//       steamCost: null,
//       hotCost: null,
//       gasCost: 108094.4721604894
//     },
//     {
//       system: "LSR系统",
//       summaryCost: null,
//       electricityCost: null,
//       waterCost: null,
//       ngCost: null,
//       steamCost: null,
//       hotCost: null,
//       gasCost: null
//     }
//   ],
//   costRatio: [
//     {
//       kind: "gas",
//       ratio: [
//         {
//           name: "废水系统",
//           value: "8704.2436104"
//         },
//         {
//           name: "UPW纯水验证线系统",
//           value: "21595.1901"
//         },
//         {
//           name: "UPW纯水生产线系统",
//           value: "108094.4721604894"
//         }
//       ]
//     }
//   ],
//   costTrend: {
//     yaxis: [
//       {
//         name: "gas",
//         value: ["138393.9058708894"]
//       }
//     ],
//     xaxis: ["202411"]
//   }
// };
const state = reactive({
  dialogAddModelVisible: false,
  loading: false,
  tableData: [],
  addModelForm: [],
  resData: {},
  activeName: "all", // 默认总能耗折标煤
  energyTypeList: [], // 耗能趋势多选
  tableHeader: [
    {
      label: "序号",
      type: "index",
      prop: "inxex"
    },
    {
      label: "系统",
      prop: "system",
      align: "left"
    },
    {
      label: "总能耗折标煤(tce)",
      prop: "summaryCost",
      align: "left",
      sortable: true
    },
    {
      label: "电消耗量(kwh)",
      prop: "electricityCost",
      align: "left",
      sortable: true
    },
    {
      label: "水消耗量(m³)",
      prop: "waterCost",
      align: "left",
      sortable: true
    },
    {
      label: "天然气消耗量(Nm³)",
      prop: "ngCost",
      align: "left",
      minwidth: "90px",
      sortable: true
    },
    {
      label: "蒸汽消耗量(t)",
      prop: "steamCost",
      align: "left",
      sortable: true
    },
    {
      label: "热水消耗量(t)",
      prop: "hotCost",
      align: "left",
      sortable: true
    },
    {
      label: "大宗气消耗量(Nm³)",
      prop: "gasCost",
      align: "left",
      minwidth: "90px",
      sortable: true
    }
  ],
  tabsOption: [
    {
      label: "all",
      name: "总能耗折标煤",
      size: "small"
    },
    {
      label: "electricity",
      name: "电",
      size: "small"
    },
    {
      label: "water",
      name: "水",
      size: "small"
    },
    {
      label: "ng",
      name: "天然气",
      size: "small"
    },
    {
      label: "steam",
      name: "蒸汽",
      size: "small"
    },
    {
      label: "hot",
      name: "热水",
      size: "small"
    },
    {
      label: "gas",
      name: "大宗气",
      size: "small"
    }
  ]
  // queryParams: {
  //   timeType: "Monthly",
  //   factory: "",
  //   timeRange: []
  // }
});
const queryParams = computed(() => props.queryParams);
const currentNode = computed(() => props.currentNode);
const { dialogAddModelVisible, loading, tableHeader, tableData, resData, activeName, tabsOption, energyTypeList, addModelForm } = toRefs(state);
const ratioChartRef = ref(null);
const trendChartRef = ref(null);
const ratioOptions = ref(null);
const trendOptions = ref(null);
const echartsKey = ref(Math.random().toString(36).slice(2, 10));

// 耗能列表的合计，正常是后端返回，后端不好整，由前端继续计算
let totalObj = {
  electricityCost: 0,
  gasCost: 0,
  hotCost: 0,
  ngCost: 0,
  steamCost: 0,
  summaryCost: 0,
  system: "合计",
  waterCost: 0
};
// 饼图
const labelLayoutFn = data => {
  const options = {
    color: ["#5B8FF9", "#5AD8A6 ", "#FFB910"],
    tooltip: {
      trigger: "item",
      formatter: `{a} <br/>{b}: {c} ({d}%)`
    },
    grid: {
      left: "0px",
      top: "40px",
      right: "10px",
      bottom: "10px",
      containLabel: true
    },
    legend: {
      orient: "horizontal", // 垂直排列
      type: "scroll", // 使用滚动的图例
      data: (data && data.map(el => el.name)) || []
    },
    series: [
      {
        name: "耗能占比",
        type: "pie",
        labelLine: {
          length: 10
        },
        label: {
          formatter: `{c|{c}} \n{d|{d}%}`,
          rich: {
            c: {
              fontSize: 16
            },
            d: {
              fontSize: 16,
              fontWeight: "bold"
            }
          }
        },
        radius: "50%",
        data: data || []
      }
    ]
  };
  if (data?.length > 0) {
    let myChart = echarts.init(ratioChartRef.value);
    myChart.setOption(options);
    ratioOptions.value = options;
  } else {
    ratioOptions.value = null;
  }
};
// 折线图
const labelLayoutFnTrend = (xData, serisData, yAxis, legend) => {
  const options = {
    tooltip: {
      trigger: "axis",
      confine: true // 确保 tooltip 显示在容器内
    },
    legend: {
      type: "scroll", // 设置图例分页类型为滚动
      icon: "rect",
      orient: "horizontal", // 水平排列
      right: "center", // 水平居中
      itemWidth: 37, // 图例标记的图形宽度
      itemHeight: 13, // 图例标记的图形高度
      selected: {},
      data: legend || []
    },
    grid: {
      left: "10px",
      right: "10px",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: xData || []
    },
    yAxis: yAxis,
    series: serisData || []
  };
  return options;
};

// const slots = useSlots();
/** 导出按钮操作 */
const handleDown = async val => {
  // 判断当前的模块 currentNode
  let name = "";
  if (currentNode.value == "fac") {
    name = "厂务侧";
  }
  if (currentNode.value == "equip") {
    name = "机台侧";
  }
  if (currentNode.value == "other") {
    name = "其他侧";
  }
  let dimension = queryParams.value.queryTimeGranularity;
  if (dimension == "Hourly") {
    dimension = "HOUR";
  }
  if (dimension == "Daily") {
    dimension = "DAY";
  }
  if (dimension == "Monthly") {
    dimension = "MONTH";
  }
  if (dimension == "Yearly") {
    dimension = "YEAR";
  }
  proxy.download(
    "post",
    "/energy/consumeMeasure/exportSummary",
    {
      dimension,
      startDate: queryParams.value.startTime,
      endDate: queryParams.value.endTime,
      factory: queryParams.value.factory,
      sysId: currentNode.value
    },
    `消耗计量-${name}耗能排行.xlsx`
  );
};
const sortTable = (v, data) => {
  if (!data || data.length <= 0) {
    tableData.value = [];
    return;
  }
  // 神拷贝
  const deepAry = JSON.parse(JSON.stringify(data));
  switch (v) {
    case "all":
      tableData.value = deepAry.sort((a, b) => {
        return b.summaryCost - a.summaryCost;
      });
      break;
    case "electricity":
      tableData.value = deepAry.sort((a, b) => {
        return b.electricityCost - a.electricityCost;
      });
      break;
    case "water":
      tableData.value = deepAry.sort((a, b) => {
        return b.waterCost - a.waterCost;
      });
      break;
    case "ng":
      tableData.value = deepAry.sort((a, b) => {
        return b.ngCost - a.ngCost;
      });
      break;
    case "steam":
      tableData.value = deepAry.sort((a, b) => {
        return b.steamCost - a.steamCost;
      });
      break;
    case "hot":
      tableData.value = deepAry.sort((a, b) => {
        return b.hotCost - a.hotCost;
      });
      break;
    case "gas":
      tableData.value = deepAry.sort((a, b) => {
        return b.gasCost - a.gasCost;
      });
      break;
    default:
      tableData.value = deepAry.sort((a, b) => {
        return b.summaryCost - a.summaryCost;
      });
      break;
  }
  // 合计保留两位小数
  Object.keys(totalObj).forEach(i => {
    if (i !== "system") {
      totalObj[i] = Number(totalObj[i]?.toFixed(2));
    }
  });
  // 把最后的合计加上
  tableData.value.push(totalObj);
};
// 耗能趋势
const handleChangeTypeFn = v => {
  // energyTypeList.value = v;
  const data = resData.value;
  let seriesArr = [];
  let yaxisArr = {};
  let legend = [];
  let xData = [];
  let danwei = "";
  if (activeName.value == "all") {
    danwei = "折标煤（tce）";
  }
  if (activeName.value == "electricity") {
    danwei = "电（kwh）";
  }
  if (activeName.value == "water") {
    danwei = "水（m³）";
  }
  if (activeName.value == "ng") {
    danwei = "天然气（Nm³）";
  }
  if (activeName.value == "steam") {
    danwei = "蒸汽（t）";
  }
  if (activeName.value == "hot") {
    danwei = "热水（t）";
  }
  if (activeName.value == "gas") {
    danwei = "大宗气（Nm³）";
  }
  yaxisArr = {
    type: "value",
    position: "left",
    name: danwei,
    alignTicks: true,
    offset: 0,
    nameTextStyle: {
      align: "left"
    },
    axisLine: {
      lineStyle: {
        width: 2
      }
    }
  };
  // 处理数据
  if (data.costTrend.axisMeasureDetailDTOS && data.costTrend.axisMeasureDetailDTOS.length > 0) {
    xData = data.costTrend.axisMeasureDetailDTOS[0].xaxis;
    data.costTrend.axisMeasureDetailDTOS.forEach((item, index) => {
      if (energyTypeList.value.includes(item.sysId)) {
        legend.push(item.sysName || item.sysId);
        let eObj = item.yaxis.find(v => v.name === activeName.value);
        seriesArr.push({
          name: item.sysName || item.sysId,
          type: "line",
          data: eObj
            ? eObj.value.map(e => {
                return Number(Number(e).toFixed(2));
              })
            : [],
          emphasis: {
            focus: "series"
          }
        });
      }
    });
  }
  trendOptions.value = labelLayoutFnTrend(xData, seriesArr, yaxisArr, legend);
  let myChart = echarts.init(trendChartRef.value);
  myChart.clear();
  myChart.setOption(trendOptions.value);
};
const tabSelectHandler = v => {
  activeName.value = v;
  // 处理排序，饼图重绘
  sortTable(v, resData.value?.costSummaryTable);
  let data = [];
  if (v !== "all") {
    const findObj = resData.value?.costRatio && resData.value?.costRatio.find(el => el.kind === v);
    data =
      (findObj &&
        findObj.ratio &&
        findObj.ratio.map(item => {
          return {
            name: item.name,
            value: item.value ? Number(item.value).toFixed(2) : 0
          };
        })) ||
      [];
    labelLayoutFn(data);
  } else {
    data = resData.value?.costSummaryTable.map(el => {
      return {
        name: el.system,
        value: el.summaryCost ? Number(el.summaryCost).toFixed(2) : 0
      };
    });
    labelLayoutFn(data);
  }
  // 耗能趋势
  if (resData.value?.costTrend && resData.value?.costTrend?.axisMeasureDetailDTOS) {
    handleChangeTypeFn(energyTypeList.value);
  }
};
const getMonthsBetweenDates = (startDate, endDate) => {
  let months = [];
  let start = new Date(startDate);
  let end = new Date(endDate);

  // 确保开始日期和结束日期是月初
  start.setDate(1);
  end.setDate(1);

  // 获取开始月份和结束月份的年份和月份
  let startYear = start.getFullYear();
  let startMonth = start.getMonth(); // 从 0 开始
  let endYear = end.getFullYear();
  let endMonth = end.getMonth(); // 从 0 开始

  // 计算从开始月份到结束月份的月份数
  for (let year = startYear, month = startMonth; year < endYear || (year === endYear && month <= endMonth); ) {
    months.push(`${year}-${(month + 1).toString().padStart(2, "0")}`); // 格式化为 'YYYY-MM'
    month++;

    // 如果当前月份超过 12 月，就切换到下一年
    if (month > 11) {
      month = 0;
      year++;
    }
  }

  return months.reverse();
};
// 点击表单
const clickFrom = async () => {
  if (queryParams.value && queryParams.value.startTime) {
    let dimension = queryParams.value.queryTimeGranularity;
    if (dimension == "Monthly") {
      dimension = "MONTH";
    }
    if (dimension == "Yearly") {
      dimension = "YEAR";
    }
    let params = {
      dimension,
      startDate: queryParams.value.startTime,
      endDate: queryParams.value.endTime,
      factory: queryParams.value.factory
    };
    // updateProduction([{ id: "", month: "2024-11-01 00:00:00", production: 101, factory: "FAC_83abf9" }]);
    // 整理日期数组
    let monthsBetween = getMonthsBetweenDates(queryParams.value.startTime, queryParams.value.endTime);
    try {
      const res = await getProductDataAPI(params);
      // 整理数据格式
      if (res && res.length > 0) {
        let obj = {};
        res.forEach(v => {
          let key = v.month.substring(0, 7);
          obj[key] = v;
        });
        let arr = [];
        monthsBetween.forEach(v => {
          let one = obj[v];
          if (one) {
            arr.push({
              factory: queryParams.value.factory,
              id: one.id,
              month: one.month,
              production: one.production
            });
          } else {
            arr.push({
              factory: queryParams.value.factory,
              id: "",
              month: v + "-01 00:00:00",
              production: ""
            });
          }
        });

        addModelForm.value = arr;
        dialogAddModelVisible.value = true;
      } else {
        // 没有数据的
        let arr = [];
        monthsBetween.forEach(v => {
          arr.push({
            factory: queryParams.value.factory,
            id: "",
            month: v + "-01 00:00:00",
            production: ""
          });
        });
        addModelForm.value = arr;
        dialogAddModelVisible.value = true;
      }
    } catch (error) {}
  }
};
const handleAddModel = async () => {
  updateProduction(addModelForm.value).then(res => {
    PxMessage.success("提交成功");
    dialogAddModelVisible.value = false;
  });
};
const getAll = async () => {
  try {
    state.loading = true;
    let dimension = queryParams.value.queryTimeGranularity;
    if (dimension == "Hourly") {
      dimension = "HOUR";
    }
    if (dimension == "Daily") {
      dimension = "DAY";
    }
    if (dimension == "Monthly") {
      dimension = "MONTH";
    }
    if (dimension == "Yearly") {
      dimension = "YEAR";
    }
    let params = {
      dimension,
      startDate: queryParams.value.startTime,
      endDate: queryParams.value.endTime,
      factory: queryParams.value.factory,
      sysId: currentNode.value
    };
    if (queryParams.value.startTime && queryParams.value.endTime) {
      const res = await getConsumptionMeasurementSummary(params);
      res?.costSummaryTable.forEach(item => {
        totalObj.electricityCost += item.electricityCost;
        totalObj.gasCost += item.gasCost;
        totalObj.hotCost += item.hotCost;
        totalObj.ngCost += item.ngCost;
        totalObj.steamCost += item.steamCost;
        totalObj.summaryCost += item.summaryCost;
        totalObj.waterCost += item.waterCost;
      });
      resData.value = res || {};
      // 趋势默认全选
      if (res?.costTrend && res?.costTrend?.axisMeasureDetailDTOS) {
        energyTypeList.value = res?.costTrend?.axisMeasureDetailDTOS.map(v => v.sysId);
      }
      tabSelectHandler("all");
    }
  } catch (error) {
  } finally {
    state.loading = false;
  }
};

onMounted(() => {
  // tabSelectHandler("all");
  // sortTable("all", resData.value.costSummaryTable);
  // 获取所有系统
  // setTimeout(() => {
  //   drawPieChart(ratioChartRef.value, resData.value.costRatio[0].ratio);
  // }, 3000);
  // drawBarChart(electricChartRef.value, res.costElectricity.xaxis, res.costElectricity.yaxis[0].value);
  // drawPieChart(ratioChartRef.value, []);
  // drawBarChart(electricChartRef.value, [], []);
  getAll();
});

// onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div class="switchTableTabs">
    <div v-loading="loading">
      <div class="tabs">
        <px-radio-group v-model="activeName" class="tabSwitch" @change="tabSelectHandler">
          <px-radio v-for="item in tabsOption" :key="item.name" size="small" :label="item.label">{{ item.name }}</px-radio>
        </px-radio-group>
      </div>
      <div class="top-card-box">
        <px-card class="card top-card top-card1">
          <div class="card-title">耗能列表</div>
          <px-button class="download" @click="handleDown">
            导出<px-icon class="px-icon--right">
              <Download />
            </px-icon>
          </px-button>
          <div class="content-table">
            <div class="left">
              <!-- <px-divider class="divider" /> -->
              <px-table height="250px" :data="tableData" size="small" border stripe show-overflow-tooltip>
                <template v-for="item in tableHeader" :key="item.prop">
                  <px-table-column v-if="item.type == 'index'" type="index" label="序号" width="60" align="center" />
                  <px-table-column
                    v-else
                    :prop="item.prop"
                    :sortable="item.prop == activeName + 'Cost'"
                    :label="item.label"
                    :min-width="item.minwidth"
                  />
                </template>
              </px-table>
            </div>
          </div>
        </px-card>
        <px-card class="card top-card top-card2">
          <div class="card-title">耗能占比</div>
          <div class="content-table">
            <div class="right">
              <!-- 饼图 -->
              <div v-show="ratioOptions" :key="echartsKey" ref="ratioChartRef" class="top-chart-bar" />
              <px-empty v-if="!ratioOptions" />
            </div>
          </div>
        </px-card>
      </div>
      <px-card class="card chartline-card">
        <div class="card-title">耗能趋势</div>
        <!-- <px-icon
          v-if="(queryParams.queryTimeGranularity == 'Yearly' || queryParams.queryTimeGranularity == 'Monthly') && queryParams.factory"
          class="fromIcon"
          size="22"
          color="#333333"
          @click="clickFrom"
          ><ViewModule
        /></px-icon> -->
        <!-- <px-checkbox-group
          v-if="resData && resData.costTrend && resData.costTrend.axisMeasureDetailDTOS"
          v-model="energyTypeList"
          @change="handleChangeTypeFn"
        >
          <px-checkbox v-for="item in resData.costTrend.axisMeasureDetailDTOS" :key="item.sysId" size="small" :label="item.sysId">{{
            item.sysName || item.sysId
          }}</px-checkbox>
        </px-checkbox-group> -->
        <div ref="trendChartRef" class="top-chart-bar" />
        <!-- <px-empty v-else /> -->
      </px-card>
    </div>
    <px-dialog v-model="dialogAddModelVisible" title="产量" width="600px">
      <px-form ref="addModelRef" label-width="80px" :model="addModelForm">
        <px-table height="340px" size="small" border :data="addModelForm" stripe show-overflow-tooltip>
          <px-table-column label="月份" min-width="200" align="left">
            <template #default="scope">
              <px-form-item label-width="0px" label=" ">{{ scope.row.month.substring(0, 7) }}</px-form-item>
            </template>
          </px-table-column>
          <px-table-column label="值" min-width="200" align="left">
            <template #default="scope">
              <px-form-item label-width="0px" label=" " :prop="scope.$index + '.production'">
                <px-input v-model.trim="scope.row.production" maxlength="20" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入" />
              </px-form-item>
            </template>
          </px-table-column>
        </px-table>
      </px-form>
      <template #footer>
        <div>
          <px-button @click="dialogAddModelVisible = false">取消</px-button>
          <px-button type="primary" @click="handleAddModel">保存</px-button>
        </div>
      </template>
    </px-dialog>
  </div>
</template>

<style lang="scss" scoped>
@import url("../scss/common.scss");
</style>
